package com.myboot.demo.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @Author: 韦溜溜
 * @Description:
 * @Date: Create in 20:36 2019/3/4
 */
@ServerEndpoint("/webSocket")
@Component
@Slf4j
public class WebSocket {

    private static CopyOnWriteArraySet<WebSocket> webSockets = new CopyOnWriteArraySet<>();

    private Session session;

    @OnOpen
    public void OnOpen(Session session){
        this.session = session;
        webSockets.add(this);
        log.info("【webSocket消息】 有新的连接，总数{}",webSockets.size());
    }

    @OnClose
    public void OnClose(){
        webSockets.remove(this);
        log.info("【webSocket消息】 关闭一个连接，总数{}",webSockets.size());
    }

    @OnMessage
    public void OnMessage(String msg){
        log.info("【webSocket消息】 收到客户端的消息，message={}",msg);
    }

    public void SendMessage(String msg){
        for (WebSocket webSocket:webSockets){
            log.info("【webSocket消息】 广播消息，message={}" ,msg);
            try {
                webSocket.session.getBasicRemote().sendText(msg);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
}
